package cn.net.dpi.core.aspect;

import cn.net.dpi.core.api.vo.Response;
import cn.net.dpi.core.exception.ApiError;
import cn.net.dpi.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Copyright(c) 2021 Dayou Positioning Intelligence Co.,Ltd
 * All rights reserved.
 *
 * 用户同意验证信息切面
 *
 * @Date 2021/9/27
 * @Author changguoshan (changguoshan@dayoupi.cn)
 * @Version 0.1
 * @Reviewer
 */
@Slf4j
@Aspect
@Component
public class UserValidAspect {

    private static final String TOKEN_NAME = "token";

    /**
     * 用户同意验证切点
     *
     * @date 2021/9/27
     */
    @Pointcut("@annotation(cn.net.dpi.core.annotation.UserValid)")
    private void cutMethod() {
    }

    /**
     * 对添加了UserValid注解的方法做用户token验证
     *
     * @date 2021/9/27
     */
    @Around(value = "cutMethod()")
    public Object doValidUser(ProceedingJoinPoint point) throws Throwable {
        try {
            /*获取到请求的属性*/
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            /*获取到请求对象*/
            assert attributes != null;
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader(TOKEN_NAME);
            if (StringUtils.isEmpty(token)) {
                return Response.error(ApiError.UNAUTHORIZED);
            }
           // log.info("用户登录验证信息token:{}", token);
            String userId = JwtUtil.getUserId(token);
            if (StringUtils.isEmpty(userId)) {
                return Response.error(ApiError.INVALID_USERID);
            }
        } catch (Exception e) {
            return Response.error(ApiError.ACCESS_DENIED);
        }
        return point.proceed();
    }
}
